import axios from "axios";
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

axios.defaults.baseURL = "/api"

const request = axios.create({
  timeout: 10000
})

const router = useRouter();

//请求拦截
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['token'] = token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data;
    console.log('Response data:', res);
    
    if (res.code === 401) {
      ElMessage.error('登录已过期，请重新登录');
      localStorage.removeItem('token');
      window.location.href = '/login';
      return Promise.reject(new Error('未登录或登录过期'));
    }
    return res;
  },
  error => {
    console.error('请求错误:', error);
    ElMessage.error(error.message || '网络请求失败');
    return Promise.reject(error);
  }
);

export default request 
